package com.tbvtc.agriculturalcreditchainserver2025.utils.aliyuyin;

import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.Resource;
import java.io.InputStream;
import java.io.IOException;

public class ByteRangeResource extends AbstractResource {

    private final Resource resource;
    private final long start;
    private final long length;

    public ByteRangeResource(Resource resource, long start, long length) {
        this.resource = resource;
        this.start = start;
        this.length = length;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream in = resource.getInputStream();
        in.skip(start);
        return new LimitedInputStream(in, length);
    }

    @Override
    public long contentLength() {
        return length;
    }

    @Override
    public String getDescription() {
        return resource.getDescription();
    }

    // 限制流大小的包装类
    private static class LimitedInputStream extends InputStream {
        private final InputStream in;
        private long remaining;

        LimitedInputStream(InputStream in, long limit) {
            this.in = in;
            this.remaining = limit;
        }

        @Override
        public int read() throws IOException {
            if (remaining <= 0) return -1;
            int data = in.read();
            if (data != -1) remaining--;
            return data;
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            if (remaining <= 0) return -1;
            int bytesToRead = (int) Math.min(len, remaining);
            int bytesRead = in.read(b, off, bytesToRead);
            if (bytesRead > 0) remaining -= bytesRead;
            return bytesRead;
        }
    }
}